package org.xx.armory.swing.components.verifiers;

import javax.swing.*;
import java.util.Date;

import static org.xx.armory.swing.UIUtils.toDateObject;

/**
 * 日期的验证器。
 * <p>此验证器进行必填校验，最大值校验和最小值校验。</p>
 */
public class DateVerifier
        implements TextVerifier {
    private final boolean required;

    /**
     * 构造输入文本校验器。
     *
     * @param required
     *         是否必填。
     */
    public DateVerifier(
            boolean required
    ) {
        this.required = required;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public VerifiedStatus verify(
            JComponent input
    ) {
        final Object obj;
        if (input instanceof JFormattedTextField) {
            obj = ((JFormattedTextField) input).getValue();
        } else {
            obj = null;
        }

        final Date value;
        if (obj instanceof Date) {
            value = (Date) obj;
        } else if (obj instanceof String) {
            value = toDateObject((String) obj);
        } else {
            value = null;
        }

        if (this.required) {
            if (value == null) {
                return VerifiedStatus.REQUIRED_ERROR;
            }
        }
        return VerifiedStatus.OK;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return "date-verify{required=" + this.required + "}";
    }
}
